/*
 * 
 * LegendShop 多用户商城系统
 * 
 *  版权所有,并保留所有权利。
 * 
 */
package com.legendshop.oa.dao.impl;

import com.legendshop.dao.impl.GenericDaoImpl;
import com.legendshop.dao.sql.ConfigCode;
import com.legendshop.dao.support.*;
import com.legendshop.dao.support.lambda.LambdaQueryMap;
import com.legendshop.oa.constants.ApplicationEnum;
import com.legendshop.oa.dao.AdminUserDao;
import com.legendshop.oa.dao.UserRoleDao;
import com.legendshop.oa.dto.AdminUserTaskEstimateDto;
import com.legendshop.oa.dto.Select2Dto;
import com.legendshop.oa.exception.BusinessException;
import com.legendshop.oa.model.AdminUser;
import com.legendshop.oa.model.Role;
import com.legendshop.oa.model.UserRole;
import com.legendshop.oa.model.UserRoleId;
import com.legendshop.oa.util.MD5Util;
import com.legendshop.util.AppUtils;
import com.legendshop.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 管理员管理
 */

public class AdminUserDaoImpl extends GenericDaoImpl<AdminUser, Long> implements AdminUserDao {

	/** The log. */
	private final static Logger log = LoggerFactory.getLogger(AdminUserDaoImpl.class);

	private UserRoleDao userRoleDao;

	public AdminUser getAdminUser(Long id) {
		return getById(id);
	}

	public int deleteAdminUser(AdminUser adminUser) {
		// 删除用户相关角色
		userRoleDao.deleteUserRoleByUserId(adminUser.getId(), ApplicationEnum.BACK_END);
		return delete(adminUser);
	}

	public Long saveAdminUser(AdminUser adminUser) {
		Long[] roleIds = adminUser.getRoleId();
		if (AppUtils.isBlank(roleIds)) {
			throw new BusinessException("role id can not empty for user " + adminUser.getId());
		}
		Long userId = save(adminUser);
		List<UserRole> userRoles = new ArrayList<UserRole>();
		for (Long roleId : roleIds) {
			UserRoleId id = new UserRoleId(userId, roleId, ApplicationEnum.BACK_END.value());
			UserRole ur = new UserRole(id);
			userRoles.add(ur);
		}
		userRoleDao.saveUserRoleList(userRoles);
		return userId;
	}

	public int updateAdminUser(AdminUser adminUser) {
		return update(adminUser);
	}

	public PageSupport<AdminUser> getAdminUser(CriteriaQuery cq) {
		return queryPage(cq);
	}

	@Override
	public Boolean isAdminUserExist(String userName) {
		List<String> list = this.query("select 1 from ls_admin_user where name = ?", String.class, userName);
		return AppUtils.isNotBlank(list);
	}

	/**
	 * 更新管理员密码
	 */
	@Override
	public int updateAdminUserPassword(Long id, String newPassword) {
		AdminUser user = getAdminUser(id);
		if (user == null) {
			log.warn("can not found user by id {}", id);
		}
		String password = MD5Util.toMD5Password(user.getName(), newPassword);
		user.setPassword(password);
		return update(user);
	}

	public void setUserRoleDao(UserRoleDao userRoleDao) {
		this.userRoleDao = userRoleDao;
	}

	@Override
	public List<Role> loadRole(String appNo) {
		return query("select * from ls_role where app_no = ?", Role.class, appNo);
	}

	@Override
	public List<Role> loadRole(Long userId, String appNo) {
		return query("SELECT *  FROM ls_role r, ls_usr_role ur WHERE ur.role_id = r.id AND ur.user_id = ? AND r.app_no = ?", Role.class, userId, appNo);
	}

	/**
	 * 按分页查询用户数据给select2使用
	 */
	@Override
	public List<Select2Dto> userList(String q, Integer pageSize, Integer currPage) {
		int offset = (currPage - 1) * pageSize;
		QueryMap map = new QueryMap();
		map.like("realName",  q);
		String querySql = ConfigCode.getInstance().getCode("oa.userList", map);
		return queryLimit(querySql, Select2Dto.class, offset,pageSize, map.toArray());
		
	}

	/**
	 * 按分页查询用户数据给select2使用, 查找我的组员
	 */
	@Override
	public List<Select2Dto> userListForMyColleague(boolean isAdmin, String q, Integer pageSize, Integer currPage, String leaderName) {
		int offset = (currPage - 1) * pageSize;
		QueryMap map = new QueryMap();
		if(!isAdmin){
			map.put("leaderName",leaderName);
		}
		map.like("realName",  q);

		String sqlId;
		if(isAdmin){//管理员
			sqlId = "oa.userListForMyColleagueAdmin";
		}else{
			sqlId = "oa.userListForMyColleague";
		}


		String querySql = ConfigCode.getInstance().getCode(sqlId, map);
		return queryLimit(querySql, Select2Dto.class, offset,pageSize, map.toArray());

	}

	
	/**
	 * 按分页查询用户数据给select2使用，选择不在团队里的组员
	 */
	@Override
	public List<Select2Dto> userListForTeam(Long projectId, String q, Integer pageSize, Integer currPage) {
		int offset = (currPage - 1) * pageSize;
		QueryMap map = new QueryMap();
		map.like("realName",  q);
		map.put("projectId", projectId);
		String querySql = ConfigCode.getInstance().getCode("oa.userListForTeam", map);
		return queryLimit(querySql, Select2Dto.class, offset,pageSize, map.toArray());
		
	}

	/**
	 * 按分页查询用户数据总数给select2使用
	 */
	@Override
	public int userCount(String q) {
		String sql = "SELECT count(*) FROM ls_admin_user";
		if(AppUtils.isNotBlank(q)) {
			sql = sql + " WHERE real_name = ?";
			return get(sql, Integer.class, q);
		}else {
			return get(sql, Integer.class);
		}
		
	}

	/**
	 * 按分页查询用户数据总数给select2使用
	 */
	@Override
	public int userCountForMyColleague(boolean isAdmin, String q, String leaderName) {
		QueryMap map = new QueryMap();
		String sql;
		if(!isAdmin){
			map.put("leaderName", leaderName);
			sql = "SELECT count(*) FROM (SELECT * FROM ls_admin_user WHERE FIND_IN_SET(NAME, getChildList(?))) u where u.need_daily_log = 1";
		}else{
			sql = "SELECT count(*) FROM ls_admin_user u where u.need_daily_log = 1";
		}

		if(AppUtils.isNotBlank(q)) {
			sql = sql + " and real_name = ?";
			map.put("realName", q);
		}
		return get(sql, Integer.class,map.toArray());
	}

	@Override
	public int userListForTeamCount(Long projectId, String q) {
		QueryMap map = new QueryMap();
		map.like("realName",  q);
		map.put("projectId", projectId);
		String querySql = ConfigCode.getInstance().getCode("oa.userListForTeamCount", map);
		return get(querySql, Integer.class,map.toArray());
	}

	/**
	 * 选择在团队里的组员
	 */
	@Override
	public List<Select2Dto> userListInTeam(Long projectId, String q, Integer pageSize, Integer currPage) {
		int offset = (currPage - 1) * pageSize;
		QueryMap map = new QueryMap();
		map.like("realName",  q);
		map.put("projectId", projectId);
		String querySql = ConfigCode.getInstance().getCode("oa.userListInTeam", map);
		return queryLimit(querySql, Select2Dto.class, offset,pageSize, map.toArray());
	}

	@Override
	public int userListInTeamCount(Long projectId, String q) {
		QueryMap map = new QueryMap();
		map.like("realName",  q);
		map.put("projectId", projectId);
		String querySql = ConfigCode.getInstance().getCode("oa.userListInTeamCount", map);
		return get(querySql, Integer.class,map.toArray());
	}

	@Override
	public String getAdminUserByName(String userName) {
		if(AppUtils.isBlank(userName)){
			return null;
		}
		//组装SQL
		StringBuffer sb = new StringBuffer("SELECT real_name FROM ls_admin_user WHERE NAME IN (");
		String[] names = userName.split(",");
		for (String name : names) {
			sb.append("'").append(name).append("',");
		}
		sb.setLength(sb.length() - 1);
		sb.append(") ORDER BY FIELD (NAME,");
		for (String name : names) {
			sb.append("'").append(name).append("',");
		}
		sb.setLength(sb.length() - 1);
		sb.append(")");
		List<String> convertResult = query(sb.toString(), String.class);
		String result = StringUtil.join(convertResult, ",");
		return result;
	}

	@Override
	public AdminUser getAdminUserByUserName(String userName) {
		if(AppUtils.isBlank(userName)){
			return null;
		}
		return getByProperties(new EntityCriterion().eq("name", userName));
	}

	/**
	 * 根据部门获取用户
	 */
	@Override
	public PageSupport<AdminUser> getAdminUserByDept(String curPageNO, AdminUser adminUser, Date startDate, Date endDate) {
		QueryMap map = new QueryMap();
		map.put("startDate", startDate);
		map.put("endDate", endDate);
		map.put("name", adminUser.getName());
		map.like("deptName", adminUser.getDeptName());
		String querySql = ConfigCode.getInstance().getCode("oa.getAdminUserByDept", map);
		String sqlCount = ConfigCode.getInstance().getCode("oa.getAdminUserByDeptCount", map);
		
		SimpleSqlQuery query = new SimpleSqlQuery(AdminUser.class,curPageNO);
		query.setPageSize(50);
		query.setAllCountString(sqlCount);
		query.setQueryString(querySql);
		query.setParam(map.toArray());
		return querySimplePage(query);
	}

	@Override
	public PageSupport<AdminUser> getAdminUser(String curPageNO, AdminUser adminUser) {
		LambdaQueryMap<AdminUser> map = new LambdaQueryMap();
		map.put(AdminUser::getName, adminUser.getName());
		map.put(AdminUser::getEnabled, adminUser.getEnabled());
		map.put(AdminUser::getRealName, adminUser.getRealName());
		map.put(AdminUser::getLeaderName, adminUser.getLeaderName());
		map.put(AdminUser::getNeedDailyLog, adminUser.getNeedDailyLog());
		SimpleSqlQuery query = new SimpleSqlQuery(AdminUser.class,50,curPageNO);
		query.setSqlAndParameter("oa.getAdminUser",map);

		return querySimplePage(query);
	}

	/**
	 * 获取每个员工在各个项目某个时段的工时统计
	 * @param userName
	 * @param startDate
	 * @param endDate
	 * @return
	 */
	@Override
	public List<AdminUserTaskEstimateDto> getAdminUserTaskEstimate(String userName, Date startDate, Date endDate) {
		return query(getSQL("oa.getAdminUserTaskEstimate"), AdminUserTaskEstimateDto.class, userName, startDate, endDate);
	}

}
